package 归并算法;

import org.junit.Test;

/**
 * @Classname reversePairs493
 * @Description TODO
 * @Date 2022/2/16 22:05
 * @Created by xjl
 */
public class reversePairs493 {

    int count = 0;

    @Test
    public void test() {
        int i = reversePairs(new int[]{2, 4, 3, 5, 1});
        System.out.println(i);
    }

    public int reversePairs(int[] nums) {
        mergeSort(nums, 0, nums.length - 1);
        return count;
    }

    void mergeSort(int[] nums, int l, int r) {
        if (l >= r) {
            return;
        }
        int mid = (l + r) / 2;
        mergeSort(nums, l, mid);
        mergeSort(nums, mid + 1, r);
        calculate(nums, l, mid, r);
        sort(nums, l, mid, r);
    }

    void calculate(int[] nums, int l, int mid, int r) {
        for (int i = l, j = mid + 1; i <= mid; i++) {
            while (j <= r && nums[i] > 2L * nums[j]) {
                j++;
            }
            count += j - (mid + 1);
        }
    }

    void sort(int[] nums, int l, int mid, int r) {
        int[] temp = new int[r - l + 1];
        int i = l, j = mid + 1;
        int index = 0;

        while (i <= mid && j <= r) {
            temp[index++] = nums[i] > nums[j] ? nums[j++] : nums[i++];
        }

        while (i <= mid) {
            temp[index++] = nums[i++];
        }
        while (j <= r) {
            temp[index++] = nums[j++];
        }

        for (int k = 0; k < temp.length; k++) {
            nums[l + k] = temp[k];
        }
    }
}
